// backend/services/wechatService.js
const axios = require('axios');
const marked = require('marked');
const fs = require('fs');
const path = require('path');
const FormData = require('form-data');
const config = require('../config');

async function getAccessToken(appId, appSecret) {
  const finalAppId = appId || config.wechat.appId;
  const finalAppSecret = appSecret || config.wechat.appSecret;

  if (finalAppId === 'YOUR_WECHAT_APP_ID' || finalAppSecret === 'YOUR_WECHAT_APP_SECRET') {
    const warningMsg = "警告：微信AppID或AppSecret未在config.js中配置，或未在测试中提供。";
    console.warn(warningMsg);
    throw new Error(warningMsg);
  }
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${finalAppId}&secret=${finalAppSecret}`;
  try {
    const response = await axios.get(url);
    if (response.data.access_token) {
      console.log("成功获取微信 Access Token。");
      return response.data.access_token;
    } else {
      throw new Error('获取微信 Access Token 失败: ' + JSON.stringify(response.data));
    }
  } catch (error) {
    console.error("请求 Access Token 时网络或配置出错:", error.message);
    throw error;
  }
}

async function uploadFromFile(accessToken, localRelativePath, uploadType = 'cover') {
  const localFilePath = path.join(__dirname, '..', 'public', localRelativePath);

  if (!fs.existsSync(localFilePath)) {
    throw new Error(`本地文件未找到: ${localFilePath}`);
  }

  const uploadUrl = uploadType === 'cover'
    ? `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${accessToken}&type=image`
    : `https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=${accessToken}`;
  
  const form = new FormData();
  form.append('media', fs.createReadStream(localFilePath));

  try {
    console.log(`[${uploadType}] 正在从本地 ${localFilePath} 上传到微信...`);
    const uploadResponse = await axios.post(uploadUrl, form, { headers: form.getHeaders() });
    
    if (uploadType === 'cover') {
        if (!uploadResponse.data.media_id) throw new Error('微信封面上传失败: ' + JSON.stringify(uploadResponse.data));
        console.log("[Cover] 图片上传成功! Media ID:", uploadResponse.data.media_id);
        return uploadResponse.data.media_id;
    } else {
        if (!uploadResponse.data.url) throw new Error('微信内联图片上传失败: ' + JSON.stringify(uploadResponse.data));
        console.log("[Inline] 图片上传成功! 微信URL:", uploadResponse.data.url);
        return uploadResponse.data.url;
    }
  } catch (error) {
    console.error(`[${uploadType}] 上传到微信时出错:`, error.message);
    throw error;
  }
}

async function pushToWechat(title, markdownContent, coverImageLocalPath) {
  const accessToken = await getAccessToken();
  if (!accessToken) {
    return { media_id: "skipped_due_to_no_config", errmsg: "未配置微信信息，跳过推送" };
  }

  // 1. 从本地文件上传封面图片
  const thumbMediaId = await uploadFromFile(accessToken, coverImageLocalPath, 'cover');

  // 2. 将Markdown转为HTML
  let htmlContent = marked.parse(markdownContent);

  // 3. 处理HTML中的所有本地图片路径
  const imgRegex = /<img src="(\/images\/.*?)"/g;
  const localImagePaths = [];
  let imgMatch;
  while ((imgMatch = imgRegex.exec(htmlContent)) !== null) {
      localImagePaths.push(imgMatch[1]);
  }

  if (localImagePaths.length > 0) {
    console.log(`在HTML内容中找到 ${localImagePaths.length} 张需要上传的内联图片。`);
    // 并行从本地上传所有内联图片到微信
    const wechatImageUrls = await Promise.all(
        localImagePaths.map(localPath => uploadFromFile(accessToken, localPath, 'inline'))
    );

    // 将HTML中的本地路径替换为微信返回的URL
    for (let i = 0; i < localImagePaths.length; i++) {
        htmlContent = htmlContent.replace(localImagePaths[i], wechatImageUrls[i]);
    }
    console.log("所有内联图片的URL已替换为微信URL。");
  }

  // 4. 构造并推送草稿
  const draftUrl = `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${accessToken}`;
  const draftData = {
    articles: [{
      title: title,
      thumb_media_id: thumbMediaId,
      content: htmlContent,
      show_cover_pic: 1,
      need_open_comment: 1,
      only_fans_can_comment: 0,
    }],
  };
  
  console.log("正在推送最终草稿到微信...");
  const draftResponse = await axios.post(draftUrl, draftData);
  
  if (draftResponse.data.errcode && draftResponse.data.errcode !== 0) {
      throw new Error('推送草稿失败: ' + JSON.stringify(draftResponse.data));
  }
  
  console.log("成功推送到微信草稿箱! Draft Media ID:", draftResponse.data.media_id);
  return draftResponse.data;
}

module.exports = { pushToWechat, getAccessToken };